<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单编号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单采购商id" prop="purchaseId" label-width="100px">
        <el-input
          v-model="queryParams.purchaseId"
          placeholder="请输入订单采购商id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="到货地址" prop="addr">
        <el-input
          v-model="queryParams.addr"
          placeholder="请输入到货地址"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['supplier:orders:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['supplier:orders:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['supplier:orders:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ordersList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="订单主键" align="center" prop="orderId"/>
      <el-table-column label="订单编号" align="center" prop="orderNo"/>
      <el-table-column label="订单简介" align="center" prop="orderDesc"/>
      <el-table-column label="订单采购商id" align="center" prop="purchaseId"/>
      <el-table-column label="到货地址" align="center" prop="addr"/>
      <el-table-column label="订单状态" align="center" prop="status"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['supplier:orders:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['supplier:orders:remove']"
          >删除
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="viewDetail(scope.row)"
          >查看详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单编号" prop="orderNo">
          <el-input v-model="form.orderNo" placeholder="请输入订单编号"/>
        </el-form-item>
        <el-form-item label="订单简介" prop="orderDesc">
          <el-input v-model="form.orderDesc" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="订单采购商id" prop="purchaseId">
          <el-input v-model="form.purchaseId" placeholder="请输入订单采购商id"/>
        </el-form-item>
        <el-form-item label="到货地址" prop="addr">
          <el-input v-model="form.addr" placeholder="请输入到货地址"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">提 交</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog title="订单详情" :visible.sync="detail_open" width="1200px" append-to-body>
      <el-table v-loading="loading" :data="goodsList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="主键" align="center" prop="goodsId"/>
        <el-table-column label="名称" align="center" prop="goodsName"/>
        <el-table-column label="单价" align="center" prop="price"/>
        <el-table-column label="图片" align="center" prop="goodsPicture">
          <template slot-scope="{ row }">
            <img
              width="50px"
              height="50px"
              v-if="row.goodsPicture"
              :src="getImage(row.goodsPicture)"
              class="avatar"
            ></img>
          </template>
        </el-table-column>
        <el-table-column label="数量" align="center" prop="amount"/>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-select v-model="warehousesId" placeholder="选择发货仓库" clearable :style="{width: '20%', margin: '20px'}">
          <el-option v-for="(item, index) in warehouses" :key="index" :label="item.label"
                     :value="item.value" :disabled="item.disabled"></el-option>
        </el-select>
        <el-button v-if="this.orderStatus === '未发货'" type="primary" @click="deliverGoods()">发 货</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listOrders, getOrders, delOrders, addOrders, updateOrders, deliver} from "@/api/supplier/orders";
import user from "@/store/modules/user";
import {listOrderDetailInfoVO} from "@/api/buyers/orderDetailInfo";
import {list3rdwarehouse} from "@/api/system/3rdwarehouse";

export default {
  name: "Orders",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单信息表格数据
      ordersList: [],
      // 订单id
      orderId: null,
      orderStatus: null,
      // 订单商品表格数据
      goodsList: [],
      // 第三方仓库
      warehouses: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否弹出详情界面
      detail_open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderNo: null,
        orderDesc: null,
        purchaseId: null,
        addr: null,
        status: null
      },
      // 表单参数
      form: {},
      // 第三方仓库Id
      warehousesId: null,
      // 表单校验
      rules: {
        purchaseId: [
          {required: true, message: "订单采购商id不能为空", trigger: "blur"}
        ],
        updateBy: [
          {required: true, message: "最新更新者id不能为空", trigger: "blur"}
        ],
      }
    };
  },
  created() {
    this.getList();
    this.get3rdstoreList();
    this.form.updateBy = user.state.id;
  },
  methods: {
    /** 查询订单信息列表 */
    getList() {
      this.loading = true;
      this.ordersList = [];
      listOrders(this.queryParams).then(response => {
        // this.ordersList = response.rows;
        response.rows.forEach((item) => {
          if (item.status === "1") {
            item.status = "未付款";
          } else if (item.status === "2") {
            item.status = "未发货";
          } else if (item.status === "3") {
            item.status = "未到货";
          } else if (item.status === "4") {
            item.status = "未签收";
          } else if (item.status === "5") {
            item.status = "完成";
          } else item.status = "未知状态";
          this.ordersList.push(item);
        })
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询订单商品列表 */
    getGoodsList(OrderId) {
      this.loading = true;
      listOrderDetailInfoVO(OrderId).then(response => {
        this.goodsList = response.rows;
        console.log("goodsList");
        console.log(this.goodsList);
        this.loading = false;
      })
    },
    get3rdstoreList() {
      list3rdwarehouse().then(response => {
        console.log(response);
        response.rows.forEach((item) => {
          this.warehouses.push({
            "label": item.warehouseName,
            "value": item.warehouseId,
          })
        })
        console.log(this.warehouses);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.detail_open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        orderId: null,
        orderNo: null,
        orderDesc: null,
        purchaseId: null,
        addr: null,
        createTime: null,
        updateTime: null,
        updateBy: user.state.id,
        status: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.orderId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加订单信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const orderId = row.orderId || this.ids
      getOrders(orderId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改订单信息";
      });
    },
    /** 修改按钮操作 */
    viewDetail(row) {
      this.detail_open = true;
      const orderId = row.orderId || this.ids
      this.orderId = orderId;
      this.orderStatus = row.status;
      this.getGoodsList(orderId);
    },
    /** 提交按钮 */
    submitForm() {
      console.log(this.form);
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.orderId != null) {
            updateOrders(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrders(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 订单发货 */
    deliverGoods() {
      if (this.warehouseId === null) {
        this.$modal.msgError("请选择出库仓库");
      }
      deliver({
        orderId: this.orderId,
        goodsList: this.goodsList,
        warehouseId: this.warehousesId,
        updateBy: user.state.id
      }).then(response => {
        console.log(response)
        console.log(response.code)
        if (response.code === 200) {
          this.$modal.msgSuccess("出库成功");
          this.detail_open = false;
        } else {
          this.$modal.msgError(response);
        }
      })
      this.getList();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const orderIds = row.orderId || this.ids;
      this.$modal.confirm('是否确认删除订单信息编号为"' + orderIds + '"的数据项？').then(function () {
        return delOrders(orderIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('supplier/orders/export', {
        ...this.queryParams
      }, `orders_${new Date().getTime()}.xlsx`)
    },
    getImage(image) {
      return `http://localhost:8080/system/common/download?name=${image}`
    },
  }
};
</script>
